<template>
    <div>
        <div class="e-table" style="background-color: #fff">
            <div class="top" v-if="!isView">
                <div class="left">
                    <div class="select_box">
                        <el-button class="btn-greenYellow" @click="onAdd">新增</el-button>
                        <el-button class="btn-delete" @click="onAdd" v-if="selectCailiaojiakoukuan.length && formData.isSystemGeneration !== 1">批量删除</el-button>
                    </div>
                </div>
            </div>
            <div class="e-tree-table">
                <div class="errorMsg" v-if="errorMsg.length>0">
                    <span >
                        {{ errorMsg.join(',') }}
                    </span>
                </div>
                <el-table
                    ref="table"
                    key="tableRef"
                    border
                    style="width: 100%"
                    row-key="uuid"
                    :data="tableData"
                    :tree-props="{
                        children: 'children',
                        hasChildren: 'hasChildren'
                    }"
                    :row-class-name="tableRowClassName"
                    @cell-mouse-enter="cellMouseEnter"
                    @cell-mouse-leave="cellMouseLeave"
                    class="table"
                    @select="onSelect"
                    @select-all="onSelectAll"
                    @selection-change="onSelectionChange"
                    :max-height="$store.state.tableHeight"
                    v-sortTable="{ 'tableData': tableData, '_this': this, 'ref': 'table' }"
                >
                    <el-table-column type="selection" fixed width="55" v-if="!isView"> </el-table-column>
                    <el-table-column label="序号" type="index" fixed width="55"> </el-table-column>
                    <el-table-column label="操作" fixed width="100" v-if="!isView">
                        <template slot-scope="{ row }">
                            <div style="display:flex; justify-content: flex-start; width: 100%;">
                                <i
                                    class="el-icon-delete"
                                    style="cursor: pointer; font-size: 20px"
                                    :class="{ 'icon-delete-active-color': MouseEnterId == row.dtlId }"
                                    @click="deleteEle(row)"
                                ></i>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="materialClassName" label="物资类别" width="250"></el-table-column>
                    <el-table-column prop="materialName" label="物资名称" min-width="150"></el-table-column>
                    <el-table-column prop="spec" align="center" label="规格型号" width="120"></el-table-column>
                    <el-table-column prop="unit" align="center" label="单位" width="120"></el-table-column>
                    <el-table-column prop="structureName" label="结构部位" width="150"></el-table-column>
                    <el-table-column prop="previousTotalConsumptionQuantity" align="right" label="截止上期末耗用数" width="200"></el-table-column>
                    <el-table-column prop="consumptionQuantity" align="right" label="本期耗用数量" width="150"></el-table-column>
                    <el-table-column prop="consumptionAmount" align="right" label="本期耗用金额" width="150"></el-table-column>
                    <el-table-column prop="plusDeductionType" label="加扣款类别" width="150">
                        <template slot-scope="{ row }">
                            <el-select v-if="!isView"
                                v-model="row.plusDeductionType"
                                placeholder="请选择"
                            >
                                <el-option
                                    v-for="item in jkkType"
                                    :key="item.kvId"
                                    :label="item.kvKey"
                                    :value="item.kvValue"
                                >
                                </el-option>
                            </el-select>
                            <span v-else>{{ getTypeLabel(row.plusDeductionType) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="quantity" align="right" label="加扣款数量" width="150">
                        <template slot-scope="{ row }">
                            <el-input v-enterFloat2 v-if="!isView"
                                placeholder="请输入加扣款数量"
                                v-model.number="row.quantity"
                            ></el-input>
                            <span v-else>{{ row.quantity }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="price" align="right" label="加扣款单价" width="150">
                        <template slot-scope="{ row }">
                            <el-input v-enterFloat v-if="!isView"
                                placeholder="请输入加扣款单价"
                                v-model.number="row.price"
                            ></el-input>
                            <span v-else>{{ row.price }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="amount" align="right" label="加扣款金额" width="150">
                        <template slot-scope="{ row }">
                            <span v-if="!isView">{{ Math.round(row.quantity * row.price * 100) / 100 }}</span>
                            <span v-else>{{ row.amount }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="taxRate" align="right" label="税率" width="150">
                        <template slot-scope="{ row }">
                            <el-input v-if="!isView"
                                placeholder="请输入税率"
                                v-model.number="row.taxRate"
                            ></el-input>
                            <span v-else>{{ row.taxRate }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="taxAmount" align="right" label="税额" width="150">
                        <template slot-scope="{ row }">
                            <span v-if="!isView">{{ row.taxRate ? Math.round((Math.round(row.quantity * row.price * 100) / 100) * row.taxRate * 100) / 100 : 0 }}</span>
                            <span v-else>{{ row.taxAmount }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="totalAmount" align="right" label="加扣款税价合计" width="150">
                        <template slot-scope="{ row }">
                            <span v-if="!isView">{{ row.taxRate ? (Math.round(row.quantity * row.price * 100) / 100) + Math.round((Math.round(row.quantity * row.price * 100) / 100) * row.taxRate * 100) / 100 : 0 }}</span>
                            <span v-else>{{ row.totalAmount }}</span>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
    </div>
</template>
<script>
// eslint-disable-next-line no-unused-vars
import { openAppClient } from '@/utils/common'
// eslint-disable-next-line no-unused-vars
import { uidBuilder } from '@/api/base/uid'
// eslint-disable-next-line no-unused-vars
import { selectDataClient, showLoading, hideLoading } from '@/utils/common'
import { mapState, mapMutations } from 'vuex'
export default {
    props: {
        tableData: {
            type: Array,
            default () {
                return []
            }
        },
        formData: {
            type: Object,
            require: true,
            default () {
                return {}
            }
        },
        isView: {
            type: Boolean,
            default: false
        }
    },
    model: {
        prop: 'contractListTable',
        event: 'change'
    },
    data () {
        return {
            MouseEnterId: 0,
            errorMsg: [],
            selectCailiaojiakoukuan: []
        }
    },
    computed: {
        ...mapState('settlementManagement', ['jkkType']),
    },
    created () {
        this.getData()
    },
    methods: {
        ...mapMutations(['setSelectedInfo']),
        getData () {

        },
        async onAdd () {
            const SelectedIDs = this.tableData.map(item => item.consumptionAllocationDtlId)
            // TODO: contractId需要更改为动态
            selectDataClient({
                SelectServiceToken: '/material/consumptionAllocation/pageDtlsForSelect', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: JSON.stringify({
                    contractId: this.formData.contractId, // 'hetong001',
                    orgId: this.formData.orgId,
                }), // 接口参数(name为模拟参数)
                Title: '选择物资' // 标题
            }).then(async res => {
                // this.setSelectedInfo(res)
                // openAppClient('/showSelectedData', '选择结果')
                // const res = [{ 'apportionedAmount': 10, 'apportionedQuantity': 10, 'billId': '1518494339923898370', 'dtlId': '1518494339923891111', 'materialClassId': '1492338036615155713/1492338402287161345/1492339386505760770', 'materialClassName': '主要材料/建筑钢材/一级钢材', 'materialId': '1492034852101296129', 'materialName': '钢材00010', 'price': 1, 'spec': '规格10', 'texture': '2', 'unit': 'T' }]
                const ids = await uidBuilder({ num: res.length })
                // 与当前表格中数据合并，已有的不覆盖
                const arr = []
                res.forEach((item, index) => {
                    const findFlag = this.tableData.find(subItem => subItem.dtlId === item.dtlId)
                    // 如果未找到，则添加到表格中
                    if (!findFlag) {
                        const apportionedQuantity = item.apportionedQuantity || 0
                        const amount = Math.round(apportionedQuantity * item.price * 100) / 100
                        arr.push({
                            consumptionAllocationBillId: item.billId,
                            consumptionAllocationDtlId: item.dtlId,
                            dtlId: '',
                            uuid: ids[index],
                            materialId: item.materialId,
                            materialName: item.materialName,
                            materialClassId: item.materialClassId,
                            materialClassName: item.materialClassName,
                            spec: item.spec,
                            unit: item.unit,
                            structureId: item.subItemId,
                            structureName: item.subItemName,
                            previousTotalConsumptionQuantity: item.previousTotalQuantity,
                            consumptionQuantity: apportionedQuantity,
                            consumptionAmount: item.apportionedAmount,
                            plusDeductionType: '2', // 默认为扣款
                            quantity: apportionedQuantity, // 默认和耗用数量一样
                            price: item.price, // 默认带入消耗单价
                            amount,
                            taxRate: '',
                            taxAmount: 0,
                            totalAmount: amount
                        })
                    }
                })
                const tableData = this.tableData.concat(arr)
                this.$emit('update:tableData', tableData)
            })
        },
        onSelect (selection, row) {
            console.log('onSelect', selection, row)
            this.selectCailiaojiakoukuan = selection
        },
        onSelectAll (selection) {
            console.log('onSelectAll', selection)
            this.selectCailiaojiakoukuan = selection
        },
        onSelectionChange (selection) {
            console.log('onSelectionChange', selection)
            this.selectCailiaojiakoukuan = selection
        },
        getTypeLabel (val) {
            const findObj = this.jkkType.find(item =>item.kvValue === val)
            return findObj ? findObj.kvKey : ''
        },
        tableRowClassName ({ row }) {
            if(row.changeType === -1) {
                return `class-${row.billId} row-hide`
            }else{
                if(row.changeState === 1) {
                    return `class-${row.billId} green row-show`
                }else if(row.changeState === 2) {
                    return `class-${row.billId} yellow row-show`
                }else if(row.changeState === -1) {
                    return `class-${row.billId} red row-show`
                }else{
                    return `class-${row.billId} row-show`
                }
            }
        },
        cellMouseEnter (row) {
            this.MouseEnterId = row.dtlId
        },
        cellMouseLeave () {
            this.MouseEnterId = 0
        }
    }
}
</script>
<style lang='scss' scoped>
    ::v-deep .hide-icon{
        .el-table__expand-icon{
            display: none;
        }
    }
    ::v-deep .el-popover__reference-wrapper{
        display: flex;
        height: 100%;
    }
    .select_box{display: flex; align-items: center;
        ::v-deep .el-radio-group{display: flex;
            .el-radio{display: flex; align-items: center; margin-right: 10px;}
        }
    }
</style>
